import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
    登录时合并购物车
    :param request: 登录的请求对象
    :param user: 登录的用户对象
    :param response: 登录的响应对象
    """

    # 获取cookie中的数据
    cart_str = request.COOKIES.get('carts')
    if cart_str is None:
        return
    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

    # 遍历同步到redis中
    redis_conn = get_redis_connection('default')
    pl = redis_conn.pipeline()
    for sku_id in cart_dict.keys():
        # 将cookie中的sku_id：count设置到hash中
        pl.hset('cart_{}'.format(user.id), sku_id, cart_dict[sku_id]['count'])
        # 如果cookie中勾选状态为true则同步到redis的set中
        if cart_dict[sku_id]['selected']:
            pl.sadd('cart_selected_{}'.format(user.id), sku_id)
    pl.execute()
    # 删除cookie中的数据
    # response.delete_cookie('carts')
